package com.lepu.app.fun.my;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import lib.share.utils.CallBack;
import lib.share.utils.PopShareShow;
import lib.share.utils.ShareUtil;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.app.application.MyApplication;
import com.app.utils.LoginUtil;
import com.app.utils.SdLocal;
import com.app.utils.Setting;
import com.app.utils.Utils;
import com.core.lib.application.BaseFragmentActivity;
import com.core.lib.core.ApiClient;
import com.core.lib.core.AsyncRequest;
import com.core.lib.utils.BrowserWebChromeClient;
import com.core.lib.utils.BrowserWebChromeClient.BrowserWebChromeDelegate;
import com.core.lib.utils.BrowserWebClient;
import com.core.lib.utils.BrowserWebClient.BrowserWebClientDelegate;
import com.core.lib.utils.main.AppManager;
import com.core.lib.utils.main.LogUtilBase;
import com.eyzhs.app.R;
import com.lepu.app.usercenter.bean.LoginInfo;
import com.lepu.app.widget.CustomTopBarNew;
import com.lepu.app.widget.CustomTopBarNew.OnTopbarNewLeftLayoutListener;

public class MyShareYaoQingCodeActivity extends BaseFragmentActivity implements
		OnTopbarNewLeftLayoutListener, AsyncRequest,
		BrowserWebChromeDelegate,BrowserWebClientDelegate {

	private static final String REQUEST_YAOQING_SHARE = "request_yaoqing_share";

	private static final String GOTO_MESSAGE = "goto::shortMessage?text=";
	private static final String GOTO_WX = "goto::weixin?text=";
	private static final String GOTO_WX_ZONE = "goto::weixinMoments?text=";
	private static final String GOTO_QQ = "goto::qq?text=";
	private static final String GOTO_QQ_ZONE = "goto::qqSpace?text=";

	private String mShareName = "";
	private String mShareInfo = "";
	private String mShareImgPath = "";
	private String mTargetUrl = "";

	private WebView mWebView = null;
	private ProgressBar mProgressBar = null;

	private CustomTopBarNew mTopbar = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {

		mNeedSwipeBack = false;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.my_share_yaoqing_code_activity);

		init();
	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@Override
	public void onResume() {
		mWebView.onResume();
		super.onResume();
	}

	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@Override
	public void onPause() {
		mWebView.onPause();
		super.onPause();
	}

	@Override
	public void onDestroy() {
		mWebView.destroy();

		super.onDestroy();
	}

	/**
	 * 添加页面动画，需要重写这个方法，
	 */
	@Override
	public void onBackPressed() {
		finishAnim(R.anim.lib_push_down_up_in, R.anim.lib_push_down_up_out);
	}

	@Override
	public void onTopbarLeftLayoutSelected() {
		finishAnim(R.anim.lib_push_down_up_in, R.anim.lib_push_down_up_out);
	}

	/**
	 * 初始化方法
	 */
	@SuppressLint("SetJavaScriptEnabled")
	private void init() {
		// topbar
		mTopbar = (CustomTopBarNew) findViewById(R.id.topbar);
		mTopbar.setTopbarTitle("邀请朋友");
		mTopbar.setonTopbarNewLeftLayoutListener(this);

		String userID = MyApplication.getInstance().getLoginInfo().UserID;
		mShareName = getString(R.string.app_name);
		// mShareInfo = String.format("我送你月子汇所500金币，注册成功后即可获取。");
		mTargetUrl = Setting.getYaoQingShareUrl(userID);// test
		mShareImgPath = SdLocal.getAppIconPath(this);

		mProgressBar = (ProgressBar) findViewById(R.id.topProgressBar);

		mWebView = (WebView) findViewById(R.id.webView);
		mWebView.setWebChromeClient(new BrowserWebChromeClient(this));
		mWebView.setWebViewClient(new BrowserWebClient(this,this,mWebView));

		Utils.initWebViewSettings(mWebView, false);

		mWebView.loadUrl(Setting.getYaoQingFriendShareUrl());
	}

	public void gotoShare(int type, String shareInfo) {

		try {
			mShareInfo = URLDecoder.decode(shareInfo, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		if (!TextUtils.isEmpty(mShareInfo)) {
			StringBuffer sb = new StringBuffer(mShareInfo);
			sb.deleteCharAt(0);
			sb.deleteCharAt(sb.toString().length() - 1);
			mShareInfo = sb.toString();
		}

		PopShareShow.mCallBack = new CallBack() {

			@Override
			public void callBackSuccess(Object obj) {
				super.callBackSuccess(obj);
				LogUtilBase.LogD(null, "回调成功 callBackSuccess");

				// requestShare();
			}

			@Override
			public void callBackFail(Object obj) {
				super.callBackFail(obj);
				LogUtilBase.LogD(null, "回调成功 callBackFail");
			}
		};

		switch (type) {
		case 0:
		case 1:

			boolean isInstallWx = AppManager.checkIfInstallApplication(this,
					"com.tencent.mm");

			if (isInstallWx) {
				if (type == 0) {
					ShareUtil.getInstance(this)
							.shareWechat(mShareName, mShareInfo, mShareImgPath,
									mTargetUrl, false, false);
				} else {
					ShareUtil.getInstance(this)
							.shareMoments(mShareName, mShareInfo,
									mShareImgPath, mTargetUrl, false, false);
				}
			} else {
				Toast.makeText(this, R.string.share_wx_reminder_message,
						Toast.LENGTH_SHORT).show();
			}
			break;
		case 2:

			ShareUtil.getInstance(this).shareQQ(mShareName, mShareInfo,
					mShareImgPath, mTargetUrl, false, false);
			break;
		case 3:
			ShareUtil.getInstance(this).shareQzone(mShareName, mShareInfo,
					mShareImgPath, mTargetUrl,false,false);
			break;
		case 4:
			ShareUtil.getInstance(this).shareSMS(mShareName,
					mShareInfo,mTargetUrl, mShareImgPath);
			break;
		default:
			break;
		}
	}

	@SuppressWarnings("unused")
	private void requestShare() {

		if (!MyApplication.getInstance().checkIsLogin()) {
			return;
		}

		String url = Setting.getShareSuccessUrl();

		Map<String, Object> map = new HashMap<String, Object>();
		JSONObject params = new JSONObject();

		try {
			params.put("DeviceID", Setting.DEVICEID);
			params.put("ApplicationID", Setting.APPLICATIONID);

			LoginInfo loginInfo = MyApplication.getInstance().getLoginInfo();
			params.put("UserID", loginInfo.UserID);
			params.put("LoginToken", loginInfo.LoginToken);

			params.put("ObjectType", 4);
			params.put("ObjectID", -1);
		} catch (Exception e) {
		}
		map.put("ht", params);

		ApiClient.http_post_main(url, map, null, this, REQUEST_YAOQING_SHARE,
				false);
	}

	@Override
	public void RequestComplete(Object object, Object data) {

		if (object.equals(REQUEST_YAOQING_SHARE)) {
			LogUtilBase.LogD(null, "share request_yaoqing_share success");
			try {
				JSONObject jsonObject = new JSONObject((String) data);
				JSONObject obj1 = (JSONObject) jsonObject.get("Result");
				JSONObject dataObject = (JSONObject) obj1.get("DetailInfo");

				int integral = dataObject.optInt("ChangeCredits");
				LoginUtil.jumpIntegral(MyShareYaoQingCodeActivity.this,
						integral);
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void RequestError(Object object, int errorId, String errorMessage) {
		if (object.equals(REQUEST_YAOQING_SHARE)) {
			LogUtilBase.LogD(null, "share request_yaoqing_share fail");
		}
	}

	public void onProgressChanged(WebView view, int newProgress) {
		// LogUtilBase.LogD(null, "onProgressChanged===>>" + newProgress);
		mProgressBar.setMax(100);
		if (newProgress < 100) {
			if (mProgressBar.getVisibility() == View.GONE) {
				mProgressBar.setVisibility(View.VISIBLE);
			}
			mProgressBar.setProgress(newProgress);
		} else {
			mProgressBar.setProgress(100);

			Animation animation = AnimationUtils.loadAnimation(this,
					R.anim.lib_broswer_progress);
			// 运行动画
			mProgressBar.startAnimation(animation);
			// 将 spinner 的可见性设置为不可见状态
			mProgressBar.setVisibility(View.GONE);
		}
	}

	// ======================================================
	@Override
	public void onPageStarted(String arg0) {
		
	}

	@Override
	public void onPageFinished(String arg0) {
		
	}

	@Override
	public boolean shouldOverrideUrlLoading(WebView webView, String url) {
		if (url.contains(GOTO_MESSAGE)) {
			gotoShare(4, url.substring(GOTO_MESSAGE.length()));
		} else if (url.contains(GOTO_WX)) {
			gotoShare(0, url.substring(GOTO_WX.length()));
		} else if (url.contains(GOTO_WX_ZONE)) {
			gotoShare(1, url.substring(GOTO_WX_ZONE.length()));
		} else if (url.contains(GOTO_QQ)) {
			gotoShare(2, url.substring(GOTO_QQ.length()));
		} else if (url.contains(GOTO_QQ_ZONE)) {
			gotoShare(3, url.substring(GOTO_QQ_ZONE.length()));
		} else {
			webView.loadUrl(url);
		}
		return true;
	}

}
